package com.promise.jokerdream.work.signin.newact

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 每日兑换礼包工作
class DailyGiftExchangeWork(uin: String): BaseWork(uin) {

    override val name: String
        get() = "每日兑换礼包"

    override val priority: Int
        get() = 3

    override val isActWork: Boolean
        get() = true
    
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 先查询每日兑换礼包信息
            val queryResult = gameApi.queryDailyGiftExchange()
            queryResult.fold(
                onSuccess = { response ->
                    // 2. 检查statuses列表，找出值为0的位置（未领取）
                    val unclaimedIndices = response.statuses.mapIndexedNotNull { index, status ->
                        if (status == 0) index else null
                    }
                    
                    if (unclaimedIndices.isNotEmpty()) {
                        // 3. 有未领取的礼包，逐个领取
                        for (index in unclaimedIndices) {
                            val claimResult = gameApi.claimDailyGiftExchange(index)
                            claimResult.fold(
                                onSuccess = { claimResponse ->
                                    historyManager.addHistory(name, claimResponse.getDescription())
                                },
                                onFailure = { exception ->
                                    historyManager.addHistory(name, exception.message)
                                }
                            )
                        }                        
                    } 
                    WorkResult.Success
                },
                onFailure = { exception ->
                    historyManager.addHistory(name, exception.message)
                    WorkResult.Failure(exception, exception.message)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}